package locations.actions;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import locations.model.Especialidad;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import locations.dao.implement.EspecialidadDAOHibernateJPA;

public class SaveSpecialityAction extends ActionSupport 
        implements ModelDriven<Especialidad>, ServletRequestAware, ServletResponseAware
{

    private static final long serialVersionUID = -8124967730231198191L;
	
    private HttpServletRequest request; 
    private HttpServletResponse response; 
    private Especialidad speciality = new Especialidad();

    public String execute()
    {
        EspecialidadDAOHibernateJPA dao = new EspecialidadDAOHibernateJPA();
        dao.save(this.speciality);
        return SUCCESS;
    }

    public Especialidad getSpeciality()
    {
        return speciality;
    }

    public void setSpeciality(Especialidad speciality)
    {
        this.speciality = speciality;
    }

    @Override
    public Especialidad getModel()
    {
        return this.speciality;
    }

    public HttpServletRequest getRequest()
    {
        return request;
    }

    public void setRequest(HttpServletRequest request)
    {
        this.request = request;
    }

    public void setResponse(HttpServletResponse response)
    {
        this.response = response;
    }

    public HttpServletResponse getResponse()
    {
        return this.response;
    }

    @Override
    public void setServletResponse(HttpServletResponse response)
    {
        this.response = response;
    }

    @Override
    public void setServletRequest(HttpServletRequest request)
    {
        this.request = request;
    }
    
    public void validate()
    {
        boolean ok = true;
        if (this.getSpeciality().getEspecialidad().equals(""))
        {
            addFieldError("especialidad", "El nombre no puede estar en blanco");
                ok = false;
        }
        if (ok)
        {
            EspecialidadDAOHibernateJPA dao = new EspecialidadDAOHibernateJPA();
            long auxId = (this.getSpeciality().getId() == null? 0 : this.getSpeciality().getId());
            if (dao.exists(this.getSpeciality().getEspecialidad(), auxId))
            {
                addFieldError("especialidad", "Ya existe una especialidad con ese nombre");
                ok = false;
            }
        }
    }
    
}
